package ro.gateway.aida.charts;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.search.ResultsFormat;
import ro.gateway.aida.search.SearchColumnDB;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.utils.Utils;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Jun 18, 2004
 * Time: 12:01:09 PM
 * To change this template use File | Settings | File Templates.
 */
public class ChartWizard$Action extends Action {
	public ActionForward execute(ActionMapping mapping,
						    ActionForm form_,
						    HttpServletRequest request,
						    HttpServletResponse response)
		  throws Exception {

		HttpSession session = request.getSession();
		ServletContext application = this.getServlet().getServletContext();
		PersistenceToken pers_token = PersistenceManager.
			  tokenLookup(application);
		ChartWizzard$ActionForm form = (ChartWizzard$ActionForm) form_;
		form.search_query = (String) session.getAttribute("search_query_for_charts");
		Utils.setBreadCrumbs(request, "bc.prjsearch.chartwizard");

		if (form.search_query == null) {
			response.sendRedirect(request.getContextPath() + "/search.do?newsearch=y");
			return null;
		}

		String jumppage = HttpUtils.getValidTrimedString(request, "jumppage", null);
		if (jumppage != null) {
			return mapping.findForward("page" + jumppage);
		}

		String page = HttpUtils.getValidTrimedString(request, "page", "1");
		page = form.populate(request, application); // returneaza pagina spre care tre' sa ma duc

		if (page == null) {
//			System.out.println("next page null");
			response.sendRedirect(request.getContextPath() + "/search.do?newsearch=y");
			return null;
		}
		return mapping.findForward("page" + page);
	}

	public static List performSearch(PersistenceToken token,
						 String search_query,
						 ResultsFormat results_format)
		  throws Exception {

		SearchColumnDB scdb = SearchColumnDB.getManager(token);
		ArrayList columns = new ArrayList();
		results_format.initTokenizer();
		while (true) {
			String c = results_format.getNextColumn();
			if (c == null) break;
			columns.add(c);
		}

		List results = scdb.createSearchResults(columns, search_query);
		System.out.println("search result set:" + columns + " : len= " + results.size());
		return results;
	}
}
